﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PTUDW_CNTN2010_F_CDT.Models;
using PagedList;

namespace PTUDW_CNTN2010_F_CDT.Controllers
{
    public class AdminCategoryController : Controller
    {
        EcommerceDBContext db = new EcommerceDBContext();

        public ActionResult ViewCategories()
        {
            return View();
        }

        public JsonResult GetListCategories(int? page, int? rows, string sidx, string sord)
        {
            var assets = from c in db.Categories
                         orderby c.CategoryName
                         select new
                         {
                             ID = c.CategoryId,
                             Name = c.CategoryName
                         };

            //var sortedAssets = assets.SortBy(sidx, sord.Contains("DESC"));
            var pagedAssets = assets.ToPagedList(page ?? 1, rows ?? 20);

            var results = new
            {
                total = pagedAssets.PageCount, //number of pages
                page = pagedAssets.PageNumber, //current page
                records = assets.Count(), //total items
                rows = pagedAssets
            };

            return Json(results);
        }

        public void Delete(int ID)
        {
            var cus = db.Categories.Find(ID);
            db.Categories.Remove(cus);
            db.SaveChanges();
        }

        [HttpPost]
        public void SaveChange(int ID, string Name)
        {
            var c = db.Categories.Find(ID);
            if (c == null)
            {
                c = new Category();
                db.Categories.Add(c);
            }
            c.CategoryName = Name;
            db.SaveChanges();
        }
    }
}
